﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using System.ServiceModel.DomainServices.Client;
using LEEAAttendanceControl.Web;
using LEEAAttendanceControl.General;
using LEEAAttendanceControl.Web.Services;
using LEEAAttendanceControl.AttendanceReference;
using System.IO;
using System.Windows.Media.Imaging;

namespace LEEAAttendanceControl.Views
{
    public partial class EmployeeEdit : ChildWindow
    {
        LEEAContext dc = new LEEAContext();
        public Employee currEmp = new Employee();

        public EmployeeEdit()
        {
            InitializeComponent();
        }

        public void LoadData(int Id)
        {
            dc.Load(dc.GetCompaniesQuery()).Completed += (s, e) =>
            {
                comboCompanies.ItemsSource = dc.Companies;

                dc.Load(dc.GetJobsQuery()).Completed += (s0, e0) =>
                {
                    comboJobs.ItemsSource = dc.Jobs;

                    dc.Load(dc.GetLocationsQuery()).Completed += (s1, e1) =>
                    {
                        combolocations.ItemsSource = dc.Locations;

                        dc.Load(dc.GetEmployeeByEmployeeIDQuery(Id)).Completed += (s2, e2) =>
                        {
                            currEmp = (Employee)dc.Employees.FirstOrDefault();

                            if (currEmp == null)
                            {
                                currEmp = new Employee();

                                dc.Employees.Add(currEmp);

                                dc.GetEmployeeMaxCode(code =>
                                {
                                    txtEmployeeCode.Text = code.Value != null ? code.Value.Value.ToString() : No.One.ToString();
                                }, null);

                                DataContext = currEmp;
                            }
                            else
                            {
                                dc.Load(dc.GetDepartmentsByCompanyIdQuery(currEmp.CompanyID.Value)).Completed += (s3, e3) =>
                                {
                                    comboCompanies.SelectedValue = currEmp.CompanyID;

                                    comboDepartments.ItemsSource = dc.Departments;

                                    DataContext = currEmp;

                                    SetFingersInfo();

                                    tabFingerInfo.Visibility = Visibility.Visible;
                                };
                                LoadImage();

                            }
                        };
                    };
                };
            };
            
        }

        void SetFingersInfo()
        {
            comboUserLevels.SelectedIndex = currEmp.UserLevel.HasValue?currEmp.UserLevel.Value:No.MinusOne;

            comboSecurityLevels.SelectedIndex =currEmp.SecurityLevel.HasValue?currEmp.SecurityLevel.Value:No.MinusOne;

            comboCardType.SelectedIndex=currEmp.CardType.HasValue?currEmp.CardType.Value:No.MinusOne;

            comboAuthMode.SelectedIndex = currEmp.AuthMode.HasValue?currEmp.AuthMode.Value:No.MinusOne;
        }

        private void OnChangesSubmitted(SubmitOperation so)
        {
            
            if (so.HasError)
            {
                so.MarkErrorAsHandled();
                MessageDisplay message = new MessageDisplay(ApplicationStrings.GeneralError
                    , ApplicationStrings.GeneralError, "Error");

                message.Show();
            }
            else
            {
                MessageDisplay message = new MessageDisplay(ApplicationStrings.GeneralSave
                    , ApplicationStrings.GeneralSave, "Save");
                message.Closed += (s, e) =>
                {
                    tabFingerInfo.Visibility = Visibility.Visible;
                };
                message.Show();
            }
        }

        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            Save();
        }

        void Save()
        {
          dc.SubmitChanges(OnChangesSubmitted, null);
        }

        private void comboCompanies_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (comboCompanies.SelectedItem != null)
            {
                dc.Load(dc.GetDepartmentsByCompanyIdQuery(Convert.ToInt32(comboCompanies.SelectedValue))
                    , OnDepartmentsLoadCompleted, null);
            }
        }

        private void OnDepartmentsLoadCompleted(LoadOperation load)
        {
            if (load.HasError)
            {
                load.MarkErrorAsHandled();
                MessageDisplay message = new MessageDisplay(ApplicationStrings.GeneralError
                    , ApplicationStrings.GeneralError, "Error");

                message.Show();
            }
            else
            {
                int? depid = currEmp.DepartmentID;

                comboDepartments.ItemsSource = load.Entities;

                comboDepartments.SelectedValue = depid;
            }
        }

        private void btnsavefinger_Click(object sender, RoutedEventArgs e)
        {
            
            if (combolocations.SelectedIndex==No.MinusOne || comboUserLevels.SelectedIndex == No.MinusOne
                || comboSecurityLevels.SelectedIndex == No.MinusOne || comboCardType.SelectedIndex == No.MinusOne || comboAuthMode.SelectedIndex == No.MinusOne)
            {
                MessageDisplay message = new MessageDisplay(ApplicationStrings.GeneralError
                    , ApplicationStrings.GeneralError, "Error");

                message.Closed += (s, ee) =>
                    {
                        return;
                    };

                message.Show();
            }

            FingerInfo fingerinfo = new FingerInfo()
                {
                    LocationId = int.Parse(combolocations.SelectedValue.ToString()),
                    Id=(uint)currEmp.EmployeeCode.Value,
                    Name=currEmp.FirstName+"-"+currEmp.LastName,
                    UserLevel = comboUserLevels.SelectedIndex,
                    SecurityLevel = comboSecurityLevels.SelectedIndex,
                    CardType = comboCardType.SelectedIndex,
                    AuthMode = comboAuthMode.SelectedIndex
                };

            AttendanceServiceClient proxy = General.General.GetProxy();

            proxy.GetFingersInfoCompleted += (s1, e1) =>
                {
                    FingerInfo fi = (FingerInfo)e1.Result;
                    currEmp.FingerTemplate = fi.FingerTemplate;
                    currEmp.FingerChecksum1 = fi.FingerChecksum1;
                    currEmp.FingerChecksum2 = fi.FingerChecksum2;
                    currEmp.UserLevel =comboUserLevels.SelectedIndex;
                    currEmp.SecurityLevel =comboSecurityLevels.SelectedIndex;
                    currEmp.CardType =comboCardType.SelectedIndex;
                    currEmp.AuthMode =comboAuthMode.SelectedIndex;
                    currEmp.Handle = fi.Handle;
                    
                    Save();
                };

            proxy.GetFingersInfoAsync(fingerinfo);
        }

        private void UploadImage_Click(object sender, RoutedEventArgs e)
        {
            if (currEmp.EmployeeID == 0)
                MessageBox.Show("You must save employee information first then upload image");
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Multiselect = false;
            dlg.Filter = "All files (*.*)|*.*|PNG Images (*.png)|*.png";

            bool? retval = dlg.ShowDialog();

            if (retval != null && retval == true)
            {
                UploadFile(dlg.File.Name, dlg.File.OpenRead());
            }
        }
        private void LoadImage(int employeeid)
        {
            string host = Application.Current.Host.Source.AbsoluteUri;
            host = host.Remove(host.IndexOf("/ClientBin"));

           this.MainImage.Source = new BitmapImage(new Uri(host+"/images/", UriKind.Absolute));
 
        }
        private void UploadFile(string fileName, Stream data)
        {
            string host = Application.Current.Host.Source.AbsoluteUri;
            host = host.Remove(host.IndexOf("/ClientBin"));

            UriBuilder ub = new UriBuilder(host + "/receiver.ashx");
            ub.Query = string.Format("filename={0}&Id={1}", fileName, currEmp.EmployeeID);
            WebClient c = new WebClient();
            c.OpenWriteCompleted += (sender, e) =>
            {
                PushData(data, e.Result);
                e.Result.Close();
                data.Close();
            };
            c.WriteStreamClosed += (sender, e) =>
            {
                LoadImage();
            };
            c.OpenWriteAsync(ub.Uri);
        }

        private void LoadImage()
        {
            try
            {
                WebClient downloader = new WebClient();
                downloader.OpenReadCompleted += new OpenReadCompletedEventHandler(downloader_OpenReadCompleted);
                string host = Application.Current.Host.Source.AbsoluteUri;
                host = host.Remove(host.IndexOf("/ClientBin"));
                string fileName = host + "/images/" + currEmp.EmployeeID.ToString() + "/" + currEmp.EmployeeID.ToString() + ".png";
                downloader.OpenReadAsync(new Uri(fileName, UriKind.Absolute));
            }
            catch { }
        }

        void downloader_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            try
            {
                BitmapImage loadedImage = new BitmapImage();
                loadedImage.SetSource(e.Result);
                MainImage.Source = loadedImage;
            }
            catch { }
        }

        private void PushData(Stream input, Stream output)
        {
            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
            {
                output.Write(buffer, 0, bytesRead);
            }
        }







    }
}
